<template>
  <main>
    <!-- Introduction -->
    <section class="mb-8 py-20 text-white text-center relative">
      <div
        class="absolute inset-0 w-full h-full bg-contain introduction-bg"
        style="background-image: url(assets/img/header.png)"
      ></div>
      <div class="container mx-auto">
        <div class="text-white main-header-content">
          <h1 class="font-bold text-5xl mb-5">{{ $t('home.listen') }}</h1>
          <p class="w-full md:w-8/12 mx-auto">
            {{ $t('home.dec') }}
          </p>
        </div>
      </div>

      <img
        class="relative block mx-auto mt-5 -mb-20 w-auto max-w-full"
        src="/assets/img/introduction-music.png"
      />
    </section>

    <!-- Main Content -->
    <section class="container mx-auto">
      <div class="bg-white rounded border border-gray-200 relative flex flex-col">
        <div
          class="px-6 pt-6 pb-5 font-bold border-b border-gray-200"
          v-icon-secondary="{ icon: 'headphones-alt', right: true }"
        >
          <span class="card-title">{{ $t('home.songs') }}</span>
          <!-- Icon -->
          <!--          <i class="fa fa-headphones-alt float-right text-green-400 text-xl"></i>-->
        </div>
        <!-- Playlist -->
        <ol id="playlist">
          <SongItem v-for="song in songs" :key="song.docID" :song="song" />
        </ol>
        <!-- .. end Playlist -->
      </div>
    </section>
  </main>
</template>
<script>
import SongItem from '@/components/SongItem.vue'
import IconSecondary from '@/directives/icon-secondary'
export default {
  directives: {
    'icon-secondary': IconSecondary
  },
  components: {
    SongItem: SongItem
  }
}
</script>
<script setup>
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import { songsCollection } from '@/includes/firebase'

const pendingRequest = ref(false)
const songs = reactive([])
const maxPerPage = ref(8)
const getSongs = async () => {
  //从数据库中获取歌曲列表
  if (pendingRequest.value) return
  pendingRequest.value = true
  let snapshots
  if (songs.length) {
    // 分页
    const lastDoc = await songsCollection.doc(songs[songs.length - 1].docID).get()
    snapshots = await songsCollection
      .orderBy('modified_name')
      .startAfter(lastDoc)
      .limit(maxPerPage.value)
      .get()
  } else {
    snapshots = await songsCollection.orderBy('modified_name').limit(maxPerPage.value).get()
  }
  snapshots.forEach((document) => {
    songs.push({
      docID: document.id,
      ...document.data()
    })
  })
  pendingRequest.value = false
}
// 分页
const handleScroll = () => {
  const { scrollTop, offsetHeight } = document.documentElement
  const { innerHeight } = window
  const bottomOfWindow = Math.round(scrollTop) + innerHeight === offsetHeight
  if (bottomOfWindow) {
    getSongs()
  }
}
onMounted(() => {
  getSongs()
  window.addEventListener('scroll', handleScroll)
})
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>
